package models

import (
	"goods-server/basic/config"
	"gorm.io/gorm"
	"time"
)

type Goods struct {
	Id         uint           `gorm:"column:id;type:bigint UNSIGNED;primaryKey;not null;" json:"id"`
	GoodsName  string         `gorm:"column:goods_name;type:varchar(255);not null;" json:"goods_name"`
	GoodsPrice uint           `gorm:"column:goods_price;type:int UNSIGNED;not null;default:0;" json:"goods_price"`
	GoodsDesc  string         `gorm:"column:goods_desc;type:varchar(255);not null;" json:"goods_desc"`
	GoodsImg   string         `gorm:"column:goods_img;type:varchar(255);not null;" json:"goods_img"`
	CreatedAt  time.Time      `gorm:"column:created_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"`
	UpdatedAt  time.Time      `gorm:"column:updated_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"`
	DeletedAt  gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

func (g *Goods) TableName() string {
	return "goods"
}

// 商品发布
func (g *Goods) CreateGoods() error {
	return config.DB.Create(&g).Error
}

// 商品列表
func (g *Goods) GetGoodsList(page, pageSize int) (goodsLists []*Goods, err error) {
	err = config.DB.Scopes(Paginate(page, pageSize)).Find(&goodsLists).Error
	return
}

// 商品详情
func (g *Goods) GetGoodsDetail() error {
	return config.DB.Where("id = ?", g.Id).Limit(1).Find(&g).Error
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
